/***************************************************************************
 *   Copyright (C) 2009-2010 by Lasse Liehu                                *
 *   lliehu@kolumbus.fi                                                    *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "failedauthenticationdialog.h"

#include <QSettings>

#include "googlelogindata.h"

FailedAuthenticationDialog::FailedAuthenticationDialog(GoogleLoginData& loginData)
        : mLoginData(loginData)
{
    ui.setupUi(this);

    setAttribute(Qt::WA_DeleteOnClose);
    ui.tryAgainButton->setDefault(true);

    connect(this, SIGNAL(accepted()), this, SLOT(slotAccepted() ));
    connect(this, SIGNAL(rejected()), this, SIGNAL(wantedToNotAskAgain() ));
}

FailedAuthenticationDialog::~FailedAuthenticationDialog()
{
}

void FailedAuthenticationDialog::readLoginData()
{
    ui.email->setText(mLoginData.email() );
    ui.password->setText(mLoginData.password(GoogleLoginData::Cached) );
}

void FailedAuthenticationDialog::on_tryAgainButton_clicked()
{
    readLoginData();
    ui.stackedWidget->setCurrentIndex(1);
    ui.loginButton->setDefault(true);
}

void FailedAuthenticationDialog::slotAccepted()
{
    mLoginData.setEmail(ui.email->text() );
    mLoginData.setPassword(ui.password->text() );
    QSettings settings(QCoreApplication::organizationName(),
                       QCoreApplication::applicationName() );
    settings.setValue("acc_email", ui.email->text());
    if (mLoginData.isPasswordSaved() )
    {
        QString password = ui.password->text();
        for (int i = 0; i < password.length(); ++i)
        {
            password[i] = QChar(password[i].unicode()+11);
        }
        settings.setValue("acc_password", password);
    }
    emit newLoginTryWanted();
}
